#include "..\CookHeader.h"

typedef struct _Store {		//  ü
	char storeName;
	int x;
	int y;
} Store;

typedef struct _StoreNode {	//   ü
	Store store;
	struct _StoreNode * link = NULL;
} StoreNode;

Array <StoreNode*> memory;
StoreNode* head, * current, * pre;

void printStores(StoreNode* start) {
	current = start;
	if (current == NULL)
		return;

	current = start;
	int x = current->store.x;
	int y = current->store.y;
	print(current->store.storeName);
	print(" Ÿ: ");
	println(to_string(sqrt(x * x + y * y)));

	while (current->link != head) {
		current = current->link;
		x = current->store.x;
		y = current->store.y;
		print(current->store.storeName);
		print(" Ÿ: ");
		println(to_string(sqrt(x * x + y * y)) );
	}
	println("");
}

void freeMemory() {	// Ҵ   ޸𸮸 Ѵ.
	for (int i = 0; i < len(memory); i++)
		delete memory[i];
}

void makeStoreList(Store store) {
	StoreNode* node = new StoreNode;
	node->store = store;
	memory.push_back(node);

	if (head == NULL) { // ù ° 
		head = node;
		node->link = head;
		return;
	}

	//   ù °   ù  
	int nodeX = node->store.x;
	int nodeY = node->store.y;
	int nodeDist = (int)sqrt(nodeX * nodeX + nodeY * nodeY);
	int headX = head->store.x;
	int headY = head->store.y;
	int headDist = (int)sqrt(headX * headX + headY * headY);

	if (headDist > nodeDist) {		//  տ  
		node->link = head;
		StoreNode* last = head;
		while (last->link != head)	//   ã
			last = last->link;
		last->link = node;
		head = node;
		return;
	}
	//  ߰  
	current = head;
	while (current->link != head) {
		pre = current;
		current = current->link;
		int currX = current->store.x;
		int currY = current->store.y;
		int currDist = (int)sqrt(currX * currX + currY * currY);
		if (currDist > nodeDist) {
			pre->link = node;
			node->link = current;
			return;
		}
	}
	//   ߰ 
	current->link = node;
	node->link = head;
}

int main() {
	randomInit(1, 100);
	Array <Store> storeArray;	

	char storeName = 'A';
	for (int i = 0; i < 10; i++) {
		int x = cookRandom(gen);
		int y = cookRandom(gen);
		Store s = { storeName, x, y };
		storeArray.push_back(s);
		storeName++; // A -> B -> C ...
	}

	for (int i = 0; i < len(storeArray); i++) {
		Store s = storeArray[i];
		makeStoreList(s);
	}
	printStores(head);

	freeMemory();
}